from flask import Flask, request, jsonify
import urllib
import os
from slide import SlideCrack

app = Flask(__name__)

def download_img(img_url, filename):
    request = urllib.request.Request(img_url)
    try:
        response = urllib.request.urlopen(request)
        if (response.getcode() == 200):
            with open(filename, "wb") as f:
                f.write(response.read()) # 将内容写入图片
            return True
    except:
        return False

@app.route('/slide-crack', methods=['GET'])
def slide_crack():
    gap_url = request.args.get('gap')
    bg_url = request.args.get('bg')
    print(f"gap_url:{gap_url}")
    print(f"bg_url:{bg_url}")
    local_gap_path = os.path.basename(os.path.normpath(gap_url))
    local_bg_path = os.path.basename(os.path.normpath(bg_url))
    download_img(gap_url, local_gap_path)
    download_img(bg_url, local_bg_path)
    sc = SlideCrack(local_gap_path, local_bg_path)
    response_data = {
        "x": sc.discern(),
    }
    os.remove(local_gap_path)
    os.remove(local_bg_path)
    return jsonify(response_data)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8787)
